package com.nhjf.mobile.controller.admin.student;


import com.nhjf.command.system.ModifyRoleCommand;
import com.nhjf.common.page.Pagination;
import com.nhjf.common.util.StringUtil;
import com.nhjf.mobile.common.util.SysProperties;
import com.nhjf.model.student.Student;
import com.nhjf.model.system.AdminSession;
import com.nhjf.model.system.Organization;
import com.nhjf.model.system.Role;
import com.nhjf.model.system.User;
import com.nhjf.model.teachers.OperationLog;
import com.nhjf.model.teachers.OrganizationHasStudent;
import com.nhjf.model.teachers.Teacher;
import org.apache.commons.lang.StringUtils;
import com.nhjf.pojo.qo.studnet.StudentQo;
import com.nhjf.pojo.qo.system.AdminSessionQo;
import com.nhjf.pojo.qo.system.OrganizationQo;
import com.nhjf.pojo.qo.system.RoleQo;
import com.nhjf.pojo.qo.system.UserQo;
import com.nhjf.pojo.qo.teachers.OrganizationHasStudentQo;
import com.nhjf.pojo.qo.teachers.TeachersQo;
import com.nhjf.service.student.StudentService;
import com.nhjf.service.system.AdminSessionService;
import com.nhjf.service.system.UserService;
import com.nhjf.service.teachers.OperationLogService;
import com.nhjf.service.teachers.OrganizationHasStudentService;
import com.nhjf.service.teachers.TeachersService;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/stu")
public class StudentAdminController  {

	@Autowired
	private StudentService studentService;
	@Autowired
	private OrganizationHasStudentService organizationHasStudentService;
	@Autowired
	private TeachersService teachersService;
	@Autowired
	private UserService userService;
	@Autowired
	private OperationLogService operationLogService;
	@Autowired
	private AdminSessionService adminSessionService;

	@RequestMapping(value = "/sutlist")
	@ResponseBody
	public String queryRoleList(HttpServletResponse response,HttpServletRequest request, Model model,@ModelAttribute OrganizationHasStudentQo stuQo,@RequestParam(value="page", defaultValue="1")Integer page,@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {

			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					if (stuQo == null) {
						stuQo = new OrganizationHasStudentQo();
					}
					if(user.getIsRole()==4) {
						resMap.put("code", "500");
						resMap.put("message", "最高管理员不能操作!");
						return JSONObject.fromObject(resMap).toString();

					}else if(user.getIsRole()==1 || user.getIsRole()==3) {
						TeachersQo qo= new TeachersQo();
						//						if(!org.apache.commons.lang.StringUtils.isEmpty(stuQo.getPhone())) {
						//							stuQo.setPhone(stuQo.getPhone());
						//						}
						//						if(!org.apache.commons.lang.StringUtils.isEmpty(stuQo.getName())) {
						//							stuQo.setName(stuQo.getName());
						//						}
						//						stuQo.setStudentId(qo.getId());
						stuQo.setIsCxdqjgxs(2);
						qo.setUserId(user.getId());
						qo.setSeachOrganization(true);
						Teacher teacher= teachersService.queryUnique(qo);
						if(teacher.getTraininginstitution()!=null && teacher.getTraininginstitution().getId()!=null ) {
							stuQo.setOrganizationId(teacher.getTraininginstitution().getId());
						}else {
							response.sendRedirect(request.getContextPath()+"/login");
						}
						Pagination pagination = new Pagination();
						pagination.setPageSize(120);
						pagination.setCondition(stuQo);
						pagination.setPageNo(page);
						pagination = organizationHasStudentService.queryPagination(pagination);
						resMap.put("stuQo", stuQo);
						//						model.addAttribute("type",2);
						resMap.put("code", "200");
						resMap.put("message",pagination);
						return JSONObject.fromObject(resMap).toString();
						//			stuQo.setOrganizationId(teacher.getTraininginstitution().getId());
						//			List<OrganizationHasStudent> list= serivce.queryList(stuQo);
						//			model.addAttribute("sList",list);
						//			return "/role/role_list.html";

					}else  {
						resMap.put("code", "500");
						resMap.put("message","其他角色不能操作!");
						return JSONObject.fromObject(resMap).toString();
					}
				}else {
					resMap.put("code", "406");
					resMap.put("message", "请先登录!");
					return net.sf.json.JSONObject.fromObject(resMap).toString();
				}
			}

			resMap.put("code", "500");
			resMap.put("message","操作异常!");
			return JSONObject.fromObject(resMap).toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message","异常抛出!");
			return JSONObject.fromObject(resMap).toString();
		} 
	}
	/**
	 * 删除学生
	 * @param request
	 * @param response
	 * @param role
	 * @param id
	 * @param model
	 * @param qo
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/student_delete")
	public String delStu(HttpServletRequest request,HttpServletResponse response ,String id,@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					if(user.getIsRole()==4) {
						resMap.put("code", "500");
						resMap.put("message","最高管理员无法操作!");
						return JSONObject.fromObject(resMap).toString();
					} else if(user.getIsRole()==1 || user.getIsRole()==3) {
						TeachersQo tqo=new TeachersQo();
						tqo.setUserId(user.getId());
						Teacher teacher=teachersService.queryUnique(tqo);
						OrganizationHasStudentQo organizationHasStudentQo=new OrganizationHasStudentQo();
						organizationHasStudentQo.setOrganizationId(teacher.getTraininginstitution().getId());//找到机构id
						organizationHasStudentQo.setStudentId(Long.parseLong(id));
						OrganizationHasStudent organizationHasStudent =organizationHasStudentService.queryUnique(organizationHasStudentQo);
						organizationHasStudentService.deleteById(organizationHasStudent.getId());
						OperationLog operationLog=new OperationLog();
						operationLog.setOperationType(1);
						operationLog.setOperationDescription("删除学生!");
						operationLog.setUserId(user);
						operationLog.setOperationTime(new Date());
						operationLog.setOperationUserName(user.getUserName());
						operationLogService.save(operationLog);
						resMap.put("code", "200");
						resMap.put("message","删除成功!");
						return JSONObject.fromObject(resMap).toString();
					}
				}else {
					resMap.put("code", "406");
					resMap.put("message", "请先登录!");
					return net.sf.json.JSONObject.fromObject(resMap).toString();
				}
			}


		}  catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message","异常抛出!");
			return JSONObject.fromObject(resMap).toString();
		}
		resMap.put("code", "500");
		resMap.put("message","操作异常!");
		return JSONObject.fromObject(resMap).toString();
	}
	@RequestMapping("/stutoadd")
	public String stutoadd() {

		return "/student/student_add.html";
	}
	/**
	 * 添加学生
	 * @param request
	 * @param response
	 * @param phone
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/stu_add",method=RequestMethod.POST)
	public String studd(HttpServletRequest request,HttpServletResponse response,String phone,@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					if(StringUtil.isNotNull(phone)) {
						/*				OrganizationHasStudentQo ohsQo=new OrganizationHasStudentQo();
						ohsQo.getOrganization().setId(oQo.getId());
						ohsQo.getStudent().setId(qo.getId());
						ohsQo=serivce.save(ohsQo);*/
						UserQo userqo=new UserQo();
						userqo.setUserName(phone);
						User users=userService.queryUnique(userqo);
						//				users.getId();
						if(null == users) {
							resMap.put("code", "500");
							resMap.put("message","没有此账号!");
							return JSONObject.fromObject(resMap).toString();
						}else {
							StudentQo suQo=new StudentQo();
							suQo.setUserid(users.getId());
							Student stu= studentService.queryUnique(suQo);
							if(stu==null) {
								resMap.put("code", "500");
								resMap.put("message","没有此学生!");
								return JSONObject.fromObject(resMap).toString();
							}
							TeachersQo tqo=new TeachersQo();
							tqo.setUserId(user.getId());
							tqo.setSeachOrganization(true);
							tqo.setSeachUser(true);
							Teacher teacher=teachersService.queryUnique(tqo);
							//					OrganizationQo oQo=new OrganizationQo();
							System.out.println(teacher.getTraininginstitution());
							System.out.println(teacher.getTraininginstitution().getId());
							if(teacher!=null && teacher.getTraininginstitution()!=null && teacher.getTraininginstitution().getId()!=null) {
								OrganizationHasStudentQo organizationHasStudentQo=new OrganizationHasStudentQo();
								organizationHasStudentQo.setOrganizationId(teacher.getTraininginstitution().getId());
								organizationHasStudentQo.setStudentId(stu.getId());
								OrganizationHasStudent organizationHasStudent= organizationHasStudentService.queryUnique(organizationHasStudentQo);
								if(organizationHasStudent==null) {
									OrganizationHasStudent ohs=new OrganizationHasStudent();
									ohs.setStudent(stu);
									Organization oiz =new Organization();
									oiz.setId(teacher.getTraininginstitution().getId());
									ohs.setOrganization(oiz);
									int i= organizationHasStudentService.ohsAdd(ohs);
									if(i==1) {
										OperationLog operationLog=new OperationLog();
										operationLog.setOperationType(2);
										operationLog.setOperationDescription("添加学生!");
										operationLog.setUserId(user);
										operationLog.setOperationTime(new Date());
										operationLog.setOperationUserName(user.getUserName());
										operationLogService.save(operationLog);
										resMap.put("code", "200");
										resMap.put("message","添加成功!");
										return JSONObject.fromObject(resMap).toString();
									}else {
										resMap.put("code", "500");
										resMap.put("message","添加失败!");
										return JSONObject.fromObject(resMap).toString();
									}
								}else {
									resMap.put("code", "500");
									resMap.put("message","此账号已存在!");
									return JSONObject.fromObject(resMap).toString();
								}
							}else {
								resMap.put("code", "500");
								resMap.put("message","没有找到机构!");
								return JSONObject.fromObject(resMap).toString();
							}
						}

					}else  {
						resMap.put("code", "500");
						resMap.put("message","请填写手机号!");
						return JSONObject.fromObject(resMap).toString();
					}
				}else {
					resMap.put("code", "406");
					resMap.put("message", "请先登录!");
					return net.sf.json.JSONObject.fromObject(resMap).toString();
				}
			}


		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message","异常抛出!");
			return JSONObject.fromObject(resMap).toString();
		}
		resMap.put("code", "500");
		resMap.put("message","操作异常!");
		return JSONObject.fromObject(resMap).toString();
	}
	/**
	 * 查看学生详情
	 * @param request
	 * @param response
	 * @param id
	 * @param qo
	 * @param model
	 * @param token
	 * @return
	 */
	@RequestMapping("/stutoview")
	@ResponseBody
	public String stutoview(HttpServletRequest request,HttpServletResponse response,String id,@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					SysProperties sysProperties=SysProperties.getInstance();
					//			 String filePath=sysProperties.get("imagePath")+"teacher/"+name+"."+extension;
					String imagePath=sysProperties.get("imagePath");
					Student stu= studentService.get(Long.parseLong(id));
					if(stu!=null ) {
						if(!StringUtils.isEmpty(stu.getAvatar())) {
							if(stu.getAvatar().indexOf(imagePath+"/picture/")>=0) {

							}else {
								stu.setAvatar(imagePath+"/picture/"+stu.getAvatar());
							}
						}
						resMap.put("code", "200");
						resMap.put("message",stu);
						return JSONObject.fromObject(resMap).toString();
					} 
				}else {
					resMap.put("code", "406");
					resMap.put("message","请先登录!");
					return JSONObject.fromObject(resMap).toString();
				}
			}
			resMap.put("code", "500");
			resMap.put("message","操作异常!");
			return JSONObject.fromObject(resMap).toString();
		} catch (Exception e) {
			// TODO: handle exception
			resMap.put("code", "500");
			resMap.put("message","异常抛出");
			return JSONObject.fromObject(resMap).toString();
		} 
	}
	/**
	 * 添加学生备注名
	 * @param id
	 * @param token
	 * @param studentNoteName
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/studentNoteName_save")
	public String studentNoteName_save(String id,@RequestParam(value="token", required=true) String token,String studentNoteName) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					if(user.getIsRole()==1 || user.getIsRole()==3) {
						StudentQo studentQo=new StudentQo();
						studentQo.setSeachStudent(true);
						studentQo.setStudentId(Long.parseLong(id));
						Student student= studentService.queryUnique(studentQo);
						student.setStudentNoteName(studentNoteName);
						studentService.update(student);
						resMap.put("code", "200");
						resMap.put("message","添加成功!");
						return JSONObject.fromObject(resMap).toString();
					}else {
						resMap.put("code", "500");
						resMap.put("message","你没权力添加备注!");
						return JSONObject.fromObject(resMap).toString();
					}
					
				}
			}
			resMap.put("code", "500");
			resMap.put("message","请先登录!");
			return JSONObject.fromObject(resMap).toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message","异常抛出!");
			return JSONObject.fromObject(resMap).toString();
		}
	}
}
